import 'dart:convert';

import 'package:custom_pop_up_menu/custom_pop_up_menu.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/base_entity.dart';
import 'package:flutter_ncsjqz_getx/model/group_details_entity.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/chat_setting/private/chat_setting_view.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/chat_window/chat_view.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/commom/address_book/address_list_logic.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/rong_base_logic.dart';
import 'package:flutter_ncsjqz_getx/util/get_user_util.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:get/get.dart';

class ItemModel {
  String title;
  String icon;
  ItemModel(this.title, this.icon);
}

class RongColudSessionListLogic extends RongBaseLogic {
  CustomPopupMenuController menuController = CustomPopupMenuController();
  GroupDetailsData groupDetailsData = GroupDetailsData();
  menuClose(){
    menuController.hideMenu();
    update();
  }
  menuOpen(){
    menuController.showMenu();
    update();
  }
  late List<ItemModel> menuItems = [
    ItemModel('发起群聊', "fqql.png"),
    ItemModel('扫一扫', "scan.png"),
    ItemModel('自我隔离', "gl.png"),
    ItemModel('添加好友', "add_circle.png"),
    ItemModel('我的二维码', "qr.png"),
  ];

  init() async{
    rongConnect();
    update();
  }

  /// 创建群聊
  createRongGroup( List<ContactInfo?> value)async{
    List createGroupData =[];
    value.forEach((element) {
      createGroupData.add(
        {
          "remarkName": element!.name,
          "userId": element.friendId,
          "ryUserId": element.ryUserId,
          "picUrl": element.img,
        }
      );
    });
    BaseEntity baseBeanEntity =await DioService<BaseEntity>().createGroup({'users':createGroupData});
    if(baseBeanEntity.code==0){
      toast("创建创建群聊成功");
      groupDetailsData = await getGroup(baseBeanEntity.data);
      Get.to(()=>ChatPage(
        conversationType: 3,
        targetId: baseBeanEntity.data,
        title: groupDetailsData.groupName,
        groupType: groupDetailsData.groupType,
        // userPic: logic.imUsersListData![index].picUrl,
        // friendId: logic.imUsersListData![index].friendId,
      ));
      // Get.to(Chat(userId: baseBeanEntity.data,messageId: '-1',name: str,conversationType: RCConversationType.Group,urls: urls,disturb: false,remaks: str,));
    }else{
      toast("创建创建群聊失败");
    }
  }

  /// 从会话列表进去聊天
  void openChat(index) async {
    if(contentList[index].menuMessageType == 2){
      groupDetailsData = await getGroup(contentList[index].targetId);
    }
    Get.to(()=>ChatPage(
      targetId: contentList[index].targetId,
      title: contentList[index].nickName,
      userPic: contentList[index].cover,
      friendId: contentList[index].userId,
      conversationType: contentList[index].menuMessageType == 2 ? 3 :1,
      groupType: groupDetailsData.groupType,
    ))!.then((value) => getConversationList());
  }

  /// 加入群聊
  void joinGroup(data) async {
    // 二维码内容json转map
    Map jsonData = json.decode(data);
    //自己邀请自己
    if(jsonData['invitation_userId'].toString() == getUserUtil().ryUserId) return toast('自己无法邀请自己进群');
    var map = {
      // 群信息
      'groupName': jsonData['name'],
      'groupId': jsonData['id'],
      'ryUserId': jsonData['invitation_ryUserId'],
      'userId': jsonData['invitation_userId'],
      'remarkName': jsonData['invitation_nikeName'],
      "users":[
        // 自己的用户信息
        {
          "picUrl":getUserUtil().picUrl,
          "ryUserId":getUserUtil().ryUserId,
          "userId":getUserUtil().userId,
          "remarkName":getUserUtil().nikeName,
        }
      ],
      // 扫码
      "joinType":2
    };
    BaseEntity baseBeanEntity =await DioService<BaseEntity>().joinGroup(map);
    if(baseBeanEntity.code == 0){
      toast("加入群聊成功，进入群聊页面");
      Get.to(()=>ChatPage(
        targetId: jsonData['id'],
        title: jsonData['name'],
        conversationType: 3,
        groupType: 2, // 加入群 是成员
      ))!.then((value) => getConversationList());
    }
  }

  /// 扫码结果
  scanCode(value) {
    Map jsonData = json.decode(value);
    if(jsonData["type"] == 1){
      // 单聊加好友
      Get.to(()=>ChatSettingPage(
        ryUserId: jsonData["ryUserId"].toString(),
        friendId: jsonData["userId"],
        type: 2,
      ),preventDuplicates:false);
    }else if(jsonData["type"] == 2){
      // 加入群聊
      joinGroup(value);
    }else{
      toast("该二维码非本平台二维码");
    }
  }
}
